package com.browser;

import java.io.*;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * 模拟一个浏览器(客户端)
 */
public class Client {
    public static void main(String[] args) {
        //启动客户端
        new Client().open();
    }

    private Socket socket;

    //2、打开一个浏览器，输入一个url ip:port/context?key=value
    //设计一个方法
    private void open() {
        System.out.println("===打开浏览器==");
        System.out.println("请输入一个请求的url:");
        Scanner input = new Scanner(System.in);
        //读取输入的一行
        String url = input.nextLine();
        //解析urL
        parseurl(url);
    }


    //3、解析url  ip port context?key=value
    private void parseurl(String url) {
        //ip:port/context?key=value
        int index1 = url.indexOf(":");//冒号的位置
        int index2 = url.indexOf("/");//返回 /的位置
        //获取ip
        String ip = url.substring(0, index1);
        //获取端口
        int port = Integer.parseInt(url.substring(index1 + 1, index2));
        //获取context的内容 ===>context?key=value
        String context = url.substring(index2 + 1);
        createSocketAndSendRequest(ip, port, context);
    }

    //4、创建一个连接
    //5、发送请求给服务器（输出流）
    private void createSocketAndSendRequest(String ip, int port, String context) {
        //创建socket
        try {
            socket = new Socket(ip, port);
            OutputStream outputStream = socket.getOutputStream();
            PrintWriter printWriter = new PrintWriter(outputStream);
            printWriter.println(context);
            printWriter.flush();
            //接受响应的信息
            this.receiveResponse();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    //6、读取服务器写回来的相应响应信息（String）
    private void receiveResponse() {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String responseContent = reader.readLine();
            while (responseContent != null && "" != responseContent) {
                System.out.println(responseContent);
                responseContent = reader.readLine();
            }
            this.parseResponseContent(responseContent);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 7、解析响应信息， 浏览器中展示出来
     *
     * @param responseContent
     */
    private void parseResponseContent(String responseContent) {
        System.out.println(responseContent);
    }
}
